﻿namespace Attacher
{
	using System.Windows;

	using Microsoft.Practices.Unity;

	using Application = System.Windows.Application;

	public partial class App : Application
	{
		#region Attributes

		private readonly IUnityContainer container;

	    private IUnhandledExceptionReportingService unhandledExceptionReportingService;

		#endregion

		public App()
		{
			this.container = new UnityContainer();

			this.container.RegisterType<IRegistrationService, RegistrationService>();
			this.container.Resolve<IRegistrationService>().Register();

			this.Exit += this.ApplicationOnExit;
		}

		public void ApplicationOnStartup(object sender, StartupEventArgs e)
		{
            MainWindow mainWindow = this.container.Resolve<IAttacherIconFactory>().Create();
		    
            IExceptionReportingServicesRegistrar exceptionReportingServicesRegistrar = this.container.Resolve<IExceptionReportingServicesRegistrar>();
            exceptionReportingServicesRegistrar.RegisterServices(mainWindow.TaskbarIcon);

            this.unhandledExceptionReportingService = this.container.Resolve<IUnhandledExceptionReportingService>();
            this.unhandledExceptionReportingService.Start();

            // Attach to the hot key
			this.container.Resolve<IAttacherService>().Enable();
            
			// Show the application icon
			mainWindow.Show();
		}

		private void ApplicationOnExit(object sender, ExitEventArgs e)
		{
            this.unhandledExceptionReportingService.Stop();
			this.container.Dispose();
			this.Exit -= this.ApplicationOnExit;

			e.ApplicationExitCode = 0;
		}
	}
}
